package com.vcredit.creditcat.service.speedloan.hl;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.vcredit.creditcat.dto.speedloan.CheckCustResultDto;
import com.vcredit.creditcat.model.AuthIdentity;
import com.vcredit.creditcat.model.Cust;
import com.vcredit.creditcat.model.ProductCheckcustItem;
import com.vcredit.creditcat.service.AuthIdentityService;
import com.vcredit.creditcat.service.speedloan.CommonProductCheckCustService;
import com.vcredit.creditcat.service.speedloan.ProductCheckCustServiceAdaptor;
import com.vcredit.creditcat.util.RSAUtil;
import com.vcredit.creditcat.vo.product.hl.HlReturnInfoVo;
import com.vcredit.framework.annotation.Log;
import com.vcredit.framework.util.HttpRequest;
import com.vcredit.framework.util.JacksonUtil;

@Service(ProductCheckCustServiceAdaptor.BEANNAME_PREFIX + 31)
public class HlCheckCustService extends CommonProductCheckCustService {

	private static Logger logger = LoggerFactory.getLogger(HlCheckCustService.class);

	@Autowired
	private AuthIdentityService authIdentityService;

	// 对接所用url

	@Value("${product.hl.url}")
	private String creditHLUrl;
	// 公钥
	@Value("${xinyongmao.publicKey}")
	private String publicKey;
	// 私钥
	@Value("${xinyongmao.privateKey}")
	private String privateKey;

	private static final String productType = "XYM";
	private static final String birdException = "还乐调用决策异常！";
	private static final String status = "1";
	private static final String refuse = "0";
	@Override
	@Log
	public CheckCustResultDto handlerCheckItem(ProductCheckcustItem checkItem, int itemType, Cust cust, Long productId) {
		try {
			int itemId = Integer.parseInt(checkItem.getCheckItemId() + "");
			if (itemType == 0) { 
				switch (itemId) {
				case 1:
					// 1.验证是否可交单
					HlReturnInfoVo infoVo = this.commitOrNot(this.getProductCheckCreditParam(cust));
					logger.info("还乐验证是否可交单！"+infoVo.getStatus()+infoVo.getMsg());
					if (status.equals(infoVo.getStatus())) {
						return CheckCustResultDto.success();
					} else if(refuse.equals(infoVo.getStatus())){
						return CheckCustResultDto.fail(infoVo.getMsg());
					}else{
						throw new Exception("请求异常~！");
					}
				default:
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(birdException,e);
			// TODO: handle exception
			//return CheckCustResultDto.fail(e.getMessage());
		}
		return CheckCustResultDto.success();
	}

	/**
	 * 封装壮库信息
	 * 
	 * @param cust
	 * @return
	 */
	public Object getProductCheckCreditParam(Cust cust) {
		Long lastProccessId = cust.getLastProccessId();
		AuthIdentity identity = authIdentityService.findByProcessId(lastProccessId);
		Map<String, String> map = new HashMap<>();
		map.put("identityNo", identity.getCitizenId());// 身份证号
		map.put("userName", identity.getName());// 用户姓名
		map.put("facePairResult", identity.getLiveCompareValue() + "");// 活体分值(新增参数)
		map.put("productType", productType);// 产品类型(固定XYM)
		logger.info(" 身份证号"+identity.getCitizenId()+" 用户姓名"+identity.getName()+"活体分值"+identity.getLiveCompareValue());
		return map;
	}

	/**
	 * 是否可交单
	 * 
	 * @param submitDto
	 * @return
	 * @throws Exception
	 */
	@Log
	public HlReturnInfoVo commitOrNot(Object submitDto) throws Exception {
		HlReturnInfoVo authPersonal = null;
		try {
			logger.info(creditHLUrl.concat("check/isReceiveCustomers"));
			String resultJson = HttpRequest.doJson(creditHLUrl.concat("check/isReceiveCustomers"), this.encodeJsonParam(JacksonUtil.Obj2Json(submitDto)));
			String decodeJsonParam = this.decodeJsonParam(resultJson);
			authPersonal = JacksonUtil.Json2Obj(decodeJsonParam, new TypeReference<HlReturnInfoVo>() {
			});
		} catch (Exception e) {
			logger.error("还乐验证黑名单出错!",e);
		}
		return authPersonal;
	}

	private String encodeJsonParam(String jsonParam) throws UnsupportedEncodingException, Exception {
		// 加密
		String requestContentBase64 = Base64.encodeBase64String(RSAUtil.encryptByPrivateKey(jsonParam.getBytes("utf-8"), this.privateKey));
		return requestContentBase64;
	}

	private String decodeJsonParam(String respJson) throws Exception {
		String result = "";
		// 解密
		byte[] res = RSAUtil.decryptBASE64(respJson);
		result = new String(RSAUtil.decryptByPublicKey(res, this.publicKey));
		return result;
	}
}
